package cn.huhaoran.yaoyaolingxian.ui;

import cn.huhaoran.yaoyaolingxian.ui.CustomTreeTableImpl.CreateGitBranchTreeTableUtils;
import cn.huhaoran.yaoyaolingxian.ui.CustomTreeTableImpl.GitBranchNode;
import cn.huhaoran.yaoyaolingxian.util.YaoYaoLingXianUtils;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.project.Project;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import org.jdesktop.swingx.JXTreeTable;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class ExportImportBranchByAFileDialog extends JFrame {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private TextFieldWithBrowseButton projectPathButton;
    private JTextField exportFileName;
    private TextFieldWithBrowseButton exportPathButton;
    private TextFieldWithBrowseButton gitPathButton;
    private JButton exportButton;
    private JButton fetchButton;
    private JButton currentBranchButton;
    private JCheckBox selectAllCheckBox;
    private JButton importButton;
    private JXTreeTable exportTable;
    private JXTreeTable importTable;
    private JTextField tipsTextField;
    private JCheckBox useUtf8CheckBox;
    private TextFieldWithBrowseButton importPathButtor;
    private JButton refreshBranchButton;
    private JCheckBox allImportCheckBox;
    private JPanel exportJPanel;
    private JPanel importJPanel;
    private JButton getTheLatestFilesButton;
    private Project project;
    public GitBranchNode exportRootNode;
    private GitBranchNode importRootNode;

    public JButton getRefreshBranchButton() {
        return refreshBranchButton;
    }
    public JPanel getExportJPanel() {
        return exportJPanel;
    }

    public JPanel getImportJPanel() {
        return importJPanel;
    }

    public ExportImportBranchByAFileDialog() {
        this.project =  YaoYaoLingXianUtils.getActiveProject();
        // 获取屏幕尺寸
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        int height = ge.getDefaultScreenDevice().getDisplayMode().getHeight();
        int width = ge.getDefaultScreenDevice().getDisplayMode().getWidth();
        // 计算对话框在屏幕中心的位置
        int x = (width - 650) / 2;
        int y = (height - 600) / 2;
        // 设置对话框的位置
        this.setLocation(x, y);
        Image image = YaoYaoLingXianUtils.loadIconAsImage("/icons/pluginIcon.svg", this.getClass());
        // 设置弹框的图标
        this.setIconImage(image);
        this.setTitle("导入/导出分支到文件");

        setContentPane(contentPane);
        //getRootPane().setDefaultButton(buttonOK);
        // todo 从持久化文件读取项目路径，如果没有保存则设置为当前项目路径
        projectPathButton.setText(project.getBasePath());
        exportPathButton.setText(project.getBasePath());
        String gitExecutablePath = YaoYaoLingXianUtils.getGitExecutablePath();
        if (gitExecutablePath != null) {
            gitPathButton.setText(gitExecutablePath);
        }else{
            SwingUtilities.invokeLater(() ->YaoYaoLingXianUtils.showMessgerOnBalloon(gitPathButton, "没有找到git可执行文件，请手动设置，如果没有进行设置将采用默认git命令，在没有配置环境变量的情况下有可能失败！"));
        }
        // 设置默认焦点
        //SwingUtilities.invokeLater(() -> this.fetchButton.requestFocusInWindow());
        // 初始化 exportFileName
        initExportFileName();

        // *************************************处理表格数据*******************************

        // --------------------------------exportTable ------------------------------
        //CreateGitBranchTreeTableUtils.initExportTable(project, exportTable,this.exportRootNode);
        // 使用工具类初始化 exportTable 组件
        this.exportRootNode = CreateGitBranchTreeTableUtils.setupGitBranchTreeTable(project, exportTable);
        // 自动展开到当前分支
        CreateGitBranchTreeTableUtils.expandToCurrentBranch(exportTable, this.exportRootNode);
        // 检查是否有足够的列可以移除
        if (exportTable.getColumnModel().getColumnCount() > 3) {
            exportTable.getColumnModel().removeColumn(exportTable.getColumnModel().getColumn(3));
        }
        fetchButton.addActionListener(e-> {
            // 使用工具类初始化 exportTable 组件
            this.exportRootNode = CreateGitBranchTreeTableUtils.setupGitBranchTreeTable(project, exportTable);
            // 自动展开到当前分支
            CreateGitBranchTreeTableUtils.expandToCurrentBranch(exportTable, this.exportRootNode);
            // 检查是否有足够的列可以移除
            if (exportTable.getColumnModel().getColumnCount() > 3) {
                exportTable.getColumnModel().removeColumn(exportTable.getColumnModel().getColumn(3));
            }
        });

        // ----------------------------------importTable ------------------------------
        setupImportPathButton();
        setupImportButton();
        // 自动扫描项目根目录的.bundle文件，并自动选择创建事件最晚的bundle文件
        String newBundleFileByPath = YaoYaoLingXianUtils.getNewBundleFileByPath(projectPathButton.getText());
        if (newBundleFileByPath != null) {
            importPathButtor.setText(newBundleFileByPath);
            setImportTableData();
        }
        // ============== 监听事件 ====================
        // 导入刷新分支按钮
   /*     fetchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CreateGitBranchTreeTableUtils.initExportTable(project, exportTable,this.exportRootNode);
            }
        });*/
        // 导出刷新分支按钮
        refreshBranchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                GitRepositoryManager repositoryManager = GitRepositoryManager.getInstance(project);
                List<GitRepository> repositories = repositoryManager.getRepositories();
                if (!repositories.isEmpty()) {
                    GitRepository gitRepository = repositories.get(0);
                    SwingUtilities.invokeLater(gitRepository::update);
                    gitRepository.update();
                }
                //ActionManager.getInstance().getAction("Synchronize").actionPerformed(null);
            }
        });
        // 处理 exportButton 点击事件
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onExport();
            }
        });
        // 确认按钮监听事件
        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });
        // 取消按钮监听事件
        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // 点击 X 时调用 onCancel()
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // 遇到 ESCAPE 时调用 onCancel()
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        // 获取最新bundle文件并刷新
        getTheLatestFilesButton.addActionListener(e -> {
            // 自动扫描项目根目录的.bundle文件，并自动选择创建事件最晚的bundle文件
            String newBundleFileByPath2 = YaoYaoLingXianUtils.getNewBundleFileByPath(projectPathButton.getText());
            if (newBundleFileByPath2 != null) {
                importPathButtor.setText(newBundleFileByPath2);
                setImportTableData();
            }
        });
        /**
         * ExportImportBranchByAFileDialog 测试新功能
         * @author huhaoran
         * @date 2024/9/6
         *
         * @param    
         * @return 
         */
        refreshBranchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
            }
        });
    }


    private void initExportFileName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd-HHmm");
        String timestamp = dateFormat.format(new Date());
        String fileName = "out_" + timestamp + ".bundle";
        exportFileName.setText(fileName); // 设置 exportFileName 的值
    }

    private void onOK() {
        // 在此处添加您的代码
        dispose();
    }

    private void onCancel() {
        // 必要时在此处添加您的代码
        dispose();
    }

    private void createUIComponents() {
        // TODO: place custom component creation code here
    }
    /**
     * setupImportPathButton 导入按钮事件
     * @author huhaoran
     * @date 2024/8/12
     *
     * @param
     * @return void
     */
    private void setupImportPathButton() {
        // 创建一个文件选择器，只允许选择 .bundle 文件
        FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(true, false, false, false, false, false) {
            @Override
            public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
                // 只显示目录和 .bundle 文件
                return file.isDirectory() || file.getName().toLowerCase().endsWith(".bundle");
            }

            @Override
            public boolean isFileSelectable(VirtualFile file) {
                // 只允许选择 .bundle 文件
                return file.getName().toLowerCase().endsWith(".bundle");
            }
        };
        fileChooserDescriptor.setTitle("选择导出的分支.bundle文件");
        importPathButtor.addBrowseFolderListener(new TextBrowseFolderListener(fileChooserDescriptor) {
            @Override
            public void onFileChosen(@NotNull VirtualFile chosenFile) {
                String selectedFilePath = chosenFile.getPath();
                importPathButtor.setText(selectedFilePath);
                // 在这里添加选择文件后的处理逻辑
                System.out.println("Selected file: " + selectedFilePath);
                setImportTableData();
            }
        });
    }
    /**
     * setImportTableData 设置输入表格数据
     * @author huhaoran
     * @date 2024/9/2
     *
     * @param
     * @return void
     */
    private void setImportTableData(){
        List<String> branches = YaoYaoLingXianUtils.getBranchesFromBundle(
                gitPathButton.getText().isEmpty() ? "git" : gitPathButton.getText(),
                project.getBasePath(),
                importPathButtor.getText(),
                useUtf8CheckBox.isSelected()
        );
        // 处理获取到的分支信息
        if (branches.isEmpty()) {
            YaoYaoLingXianUtils.showMessgerOnBalloon(importTable,"读取分支信息失败！");
        } else {
            // 在这里处理获取到的分支信息，例如显示在对话框中
            for (String branch : branches) {
                System.out.println(branch);
            }
            // 导入数据到树
            GitBranchNode gitBranchNode = CreateGitBranchTreeTableUtils.convertBranchesGitBranchNode(branches);
            importRootNode = CreateGitBranchTreeTableUtils.setupGitBranchTreeTable(gitBranchNode, importTable);
            importTable.getColumnModel().getColumn(1).setMinWidth(3);
            importTable.getColumnModel().getColumn(2).setMinWidth(3);
            importTable.getColumnModel().getColumn(1).setPreferredWidth(5);
            importTable.getColumnModel().getColumn(1).setWidth(5);
            importTable.getColumnModel().getColumn(2).setPreferredWidth(5);
            importTable.getColumnModel().getColumn(2).setWidth(5);
            importTable.getColumnModel().getColumn(3).setMinWidth(100);
            //importTable.getColumnModel().getColumn(2).setModelIndex(80);
            // 自动展开到当前分支
            CreateGitBranchTreeTableUtils.expandToCurrentBranch(importTable, importRootNode);
        }
    }
    private void setupImportButton() {
        importButton.addActionListener(e -> onImportButtonClick());
    }
    /**
     * onImportButtonClick 单击导入按钮
     * @author huhaoran
     * @date 2024/9/10
     *
     * @param
     * @return void
     */
    private void onImportButtonClick() {
        // 获取importRootNode中选中的节点
        List<GitBranchNode> selectedBranches = CreateGitBranchTreeTableUtils.getSelectedBranches(importRootNode);
        // 调用工具类执行多个git fetch命令
        int importNumber = YaoYaoLingXianUtils.getFetchByBundle(
                gitPathButton.getText().isEmpty() ? "git" : gitPathButton.getText(),
                projectPathButton.getText(),
                importPathButtor.getText(),
                selectedBranches,
                useUtf8CheckBox.isSelected()
        );
        // 显示没有git管理。。。
        //int importNumber = YaoYaoLingXianUtils.gitFetchBundle(importPathButtor.getText(),selectedBranches);
        if (importNumber != 0){
            Notifications.Bus.notify(new Notification("Print", "导入完成！",
                    "共成功导入了：" + importNumber+"个分支", NotificationType.INFORMATION), project);
        }else{
            Notifications.Bus.notify(new Notification("Print", "导入失败！",
                    "没有分支导入成功...", NotificationType.ERROR), project);
        }
    }


    /**
     * onExport 单击导出
     * @author huhaoran
     * @date 2024/8/12
     *
     * @param
     * @return void
     */
    private void onExport() {
        String exportPath = exportPathButton.getText();
        if (!exportPath.endsWith("/") && !exportPath.endsWith("\\")) {
            exportPath += System.getProperty("file.separator");
        }
        String fullPath = exportPath + exportFileName.getText();
        String gitExecutable = gitPathButton.getText().isEmpty() ? "git" : gitPathButton.getText();
        String projectPath = projectPathButton.getText(); // 获取项目路径
        String branchName;
        if (selectAllCheckBox.isSelected()) {
            branchName = "--all";
        } else {
            //branchName = getFirstSelectedBranchName(exportRootNode);
            List<GitBranchNode> selectedBranches = CreateGitBranchTreeTableUtils.getSelectedBranches(exportRootNode);
            branchName = selectedBranches.stream()
                    .map(GitBranchNode::getFullBranchName)  // 提取每个元素的 getFullBranchName 值
                    .collect(Collectors.joining(" "));     // 用空格拼接
            if (branchName == null) {
                JOptionPane.showMessageDialog(this, "请选择一个分支", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        // 执行 git bundle create 命令
        YaoYaoLingXianUtils.createGitBundle(gitExecutable, projectPath, fullPath, branchName,useUtf8CheckBox.isSelected());
    }



}
